<template>
  <div>
    <div
      class="manage_sels d-flex align-items-center"
      ref="kfs"
      v-if="showIpt"
      @click.stop="showDialog"
    >
      <span v-if="submitResult.length == 0" class="manage_tips">请选择</span>
      <i
        class="el-select__caret el-input__icon el-icon-arrow-up arrow_up"
        :class="showDia ? 'is-reverse' : ''"
      ></i>
      <!-- 模拟input框内容 start -->
      <div class="item my_ipt" ref="myipt" v-if="submitResult.length > 0">
        <el-tag
          closable
          size="small"
          type="info"
          @close="clearChoose(index, item, 1)"
          v-for="(item, index) in submitResult"
          :key="index"
          style="margin-right: 6px; margin-bottom: 6px"
        >
          {{ item ? item.name : "" }}
        </el-tag>
      </div>
    </div>
    <!-- 弹框 -->
    <el-dialog
      ref="wDialog"
      :visible="showDia"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="640px"
      @close="close"
      title="设置管理部门"
    >
      <div class="dep_container box manage_abs">
        <div class="dep_content">
          <div class="dep_left">
            <div class="left_tit">部门列表</div>
            <el-input
              prefix-icon="el-icon-search"
              placeholder="请输入搜索内容"
              class="search_ipt"
              v-model="filtersText"
            ></el-input>
            <div class="dep_tree">
              <el-tree
                :data="depTreeList"
                show-checkbox
                node-key="id"
                ref="dep_tree"
                highlight-current
                :props="defaultProps"
                :filter-node-method="filterNode"
                @check="handleCheckChange"
                :default-expanded-keys="
                  depTreeList[0] ? [depTreeList[0].deptId] : []
                "
              >
              </el-tree>
            </div>
          </div>
          <div class="dep_right">
            <div class="right_tit">
              <span>已选择部门（{{ chooseResult.length }} ）</span>
              <span @click="clearSelects">清空全部</span>
            </div>
            <div class="choose_box">
              <div
                class="item"
                style="padding: 0; margin: 0; margin-bottom: 8px"
                v-for="(item, index) in chooseResult"
                :key="index"
              >
                <el-tag
                  closable
                  type="info"
                  @close="clearChoose(index, item)"
                  color="#F6F7FC"
                  style="
                    width: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  {{ item ? item.name : "" }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canDeps">取消</el-button>
        <el-button type="primary" @click="submitDeps">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "label"
      },
      depTreeList: [], // 部门树结构
      chooseResult: [], //勾选的节点
      chooseKeys: [], //勾选的节点的key
      submitResult: [], //input框回显内容
      submitKeys: [], //input框回显内容的key
      filtersText: "", //搜索字段
      deptId: null,
      roleIdList: null,
      resultDept: null,
      showDia: false
    };
  },
  /**
   *
   * 不要改manageDeptId
   *
   */
  props: {
    manageDeptId: {}, //id 例：123,345,567
    manageDeptName: {
      default: ""
    }, //名称 例：市场运营中心,学员服务中心,财务管理中心
    showIpt: {
      default: true //是否展示input框
    },
    visible: {
      default: false //是否展示dialog
    },
    // 需要组件来回显字段名称
    isShowName: {
      defalut: false
    },
    restrictData: String
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.showDia = true;
        } else {
          this.showDia = false;
        }
        if (!this.showIpt) {
          this.clearData();
          this.initData(this.manageDeptId, 1);
        }
      },
      immediate: true
    },
    filtersText(val) {
      this.$refs.dep_tree.filter(val);
    },
    manageDeptId: {
      /**
       * input框-回显已选项
       */
      handler(val) {
        if (this.showIpt) {
          this.initData(val);
        }
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    ...mapGetters(["depAllList", "depAllTreeList"])
  },
  async mounted() {
    // r如果有过滤条件
    if (this.restrictData) {
      const str = JSON.parse(this.restrictData);
      const target = Object.prototype.toString.call(str);
      target === "[object Object]"
        ? (this.deptId = str.deptId)
        : (this.roleIdList = str);
      const res = await depListAPI({//扫码打印
        type: "tree"
      });
      this.depTreeList = res.data.map((item, index) => {
        if (this.deptId) {
          if (item.deptId != this.deptId) {
            // 筛选条件不是顶级
            item.disabled = true;
          }
          // 获取指定的树结构数据
          this.getTreeItem(item.children, this.deptId);
          item.children = [this.resultDept];
        }
        return item;
      });
    } else {
      this.deptId = null;
      this.roleIdList = null;
      this.depTreeList = this.depAllTreeList;
    }
  },
  methods: {
    // 初始化数据
    initData(val, kding) {
      if (val) {
        val = String(val);
        let selArr = val.split(",");
        let selName = this.manageDeptName.split(",");
        this.chooseKeys = selArr.length && selArr[0] != "" ? selArr : [];
        this.submitKeys = JSON.parse(JSON.stringify(selArr));
        this.chooseKeys.forEach((item, index) => {
          // 如果需要组件回显字段名称
          if (this.isShowName) {
            this.depAllList.forEach((it, i) => {
              if (+item === it.deptId) {
                this.$set(this.submitResult, index, {
                  name: it.label
                });
                this.$set(this.chooseResult, index, { name: it.label });
              }
            });
          } else {
            this.$set(this.submitResult, index, {
              name: JSON.parse(JSON.stringify(selName[index]))
            });
            this.$set(this.chooseResult, index, { name: selName[index] });
          }
        });
      } else {
        this.clearData();
        this.$nextTick(() => {
          if (this.$refs.dep_tree) {
            this.$refs.dep_tree.setCheckedKeys(this.submitKeys);
          }
        });
      }
      if (kding == 1) {
        this.showDialog();
      }
    },
    /**
     * 树结构-回显已选项
     */
    showDialog() {
      this.showDia = true;
      if (this.submitResult && this.submitResult.length > 0) {
        this.chooseKeys = JSON.parse(JSON.stringify(this.submitKeys));
        this.chooseResult = JSON.parse(JSON.stringify(this.submitResult));
        this.$nextTick(() => {
          if (this.$refs.dep_tree) {
            this.$refs.dep_tree.setCheckedKeys(this.submitKeys);
          }
        });
      }
    },
    close() {
      this.showDia = false;
      this.$emit("update:visible", false);
    },
    // 清空数据
    clearData() {
      this.chooseKeys = [];
      this.submitKeys = [];
      this.chooseResult = [];
      this.submitResult = [];
    },
    canDeps() {
      this.showDia = false;
      if (this.showIpt) {
        this.$emit("submitDeps", this.manageDeptId);
      } else {
        this.clearData();
      }
    },
    /**
     * 取差集
     */
    getDifferentArr(allArr, partArr) {
      for (let i = allArr.length - 1; i >= 0; i--) {
        for (let j = 0; j < partArr.length; j++) {
          if (allArr[i].deptId === partArr[j].deptId) {
            allArr.splice(i, 1);
            break;
          }
        }
      }
      return allArr;
    },
    /**
     * 勾选操作
     */
    handleCheckChange(data, checked, indeterminate) {
      let allnodes = this.$refs.dep_tree.getCheckedNodes();
      let allkeys = this.$refs.dep_tree.getCheckedKeys();
      let checkdChildren = []; //所有选中的子集
      allnodes.forEach((item, index) => {
        if (item.children) {
          // eachCheck 单个选中的
          let eachCheck = item.children.filter((item2, index2) => {
            return allkeys.includes(item2.deptId);
          });
          if (eachCheck && eachCheck.length > 0) {
            checkdChildren = checkdChildren.concat(eachCheck);
          }
        }
      });
      this.chooseResult = this.getDifferentArr(allnodes, checkdChildren);
      this.chooseKeys = this.chooseResult.map(item => item.deptId);
    },
    /**
     * 清空-单个
     */
    clearChoose(idx, item, type) {
      this.chooseResult.splice(idx, 1);
      this.chooseKeys.splice(idx, 1);
      this.$nextTick(() => {
        if (this.$refs.dep_tree) {
          this.$refs.dep_tree.setCheckedKeys(this.chooseKeys);
        }
      });
      if (type == 1) {
        this.submitResult.splice(idx, 1);
        this.submitKeys.splice(idx, 1);
        //改初始化数据
        this.$emit("submitDeps", this.chooseKeys.join(","));
      }
    },
    /**
     * 清空-所有
     */
    clearSelects() {
      this.chooseResult = [];
      this.chooseKeys = [];
      this.$refs.dep_tree.setCheckedNodes([]);
    },
    /**
     * 筛选
     */
    filterNode(value, data, node) {
      if (!value) return true;
      return this.chooseNode(value, data, node);
    },
    /**
     * 筛选
     */
    chooseNode(value, data, node) {
      if (data.label.indexOf(value) !== -1) {
        return true;
      }
      const level = node.level;
      if (level === 1) {
        return false;
      }
      let parentData = node.parent;
      let index = 0;
      while (index < level - 1) {
        if (parentData.data.label.indexOf(value) !== -1) {
          return true;
        }
        parentData = parentData.parent;
        index++;
      }
      return false;
    },
    /**
     * 提交操作
     */
    submitDeps() {
      if (this.showIpt) {
        this.showDia = false;
      }
      this.submitResult = JSON.parse(JSON.stringify(this.chooseResult));
      this.submitKeys = JSON.parse(JSON.stringify(this.chooseKeys));
      this.$emit("submitDeps", this.chooseKeys.join(","));
    },
    /**
     * 获取指定的数结构
     * @param {*} data 树结构
     * @param {*} id 指定的子集id
     */
    getTreeItem(data, id) {
      data.map(item => {
        if (item.deptId == id) {
          this.resultDept = item; // 结果赋值
        } else {
          if (item.children) {
            this.getTreeItem(item.children, id);
          }
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
.manage_sels {
  width: 100%;
  border-radius: 3px;
  border: 1px solid #e6e6e6;
  min-height: 34px;
  /deep/ .el-tag.el-tag--info {
    color: #333333 !important;
  }
  cursor: pointer;
  position: relative;
  padding: 0 6px;
  .manage_tips {
    color: #c0c4cc;
    line-height: 32px;
  }
  .arrow_up {
    position: absolute;
    right: 3px;
    color: #c0c4cc;
    transform: rotateZ(180deg);
  }
  .is-reverse {
    transform: rotateZ(0deg);
  }
  .manage_abs {
    position: absolute;
    z-index: 100000;
    // top: 45px;
    top: 50px;
    right: 0;
  }
  .sanjiao {
    position: absolute;
    content: "";
    top: 45px;
    right: 50px;
    width: 0;
    height: 0;
    border-bottom: 6px solid #ebeef5;
    border-right: 6px solid transparent;
    border-left: 6px solid transparent;
    display: inline-block;
  }
  .my_ipt {
    width: 100%;
    display: flex;
    align-items: center;
    min-height: 34px;
    flex-wrap: wrap;
    padding-top: 6px;
  }
  .my_ipt /deep/ .el-tag__close {
    background: #c0c4cc;
  }
}
.dep_container {
  background: white;
  width: 100%;
  height: 469px;

  .dep_content {
    display: flex;
    height: 496px;

    border: 1px solid #eeeeee;
  }
  .dep_content /deep/ .el-tree-node__content {
    height: 34px !important;
  }
  .dep_left {
    width: 300px;
    border-right: 1px solid #eeeeee;
    display: flex;
    height: 100%;
    flex-direction: column;
    .left_tit {
      height: 40px;
      background: #f6f7fc;
      font-size: 13px;
      line-height: 36px;
      color: #333333;
      padding-left: 15px;
    }
    .search_ipt {
      width: 90%;
      height: 32px;
      margin-left: 16px;
      margin-bottom: 15px;
      margin-top: 8px;
      /deep/ .el-input__inner {
        background: #f6f7fc !important;
        border: none !important;
      }
    }
    .dep_tree {
      height: calc(100% - 40px - 32px - 15px - 8px);
      overflow: scroll;
    }
     .dep_tree /deep/ .el-tree-node__label{
       overflow: hidden;
       white-space: nowrap;
       text-overflow: ellipsis;
     }
  }
  .dep_right {
    width: 300px;
    .right_tit {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      padding-left: 15px;
      padding-right: 15px;
      border-bottom: 1px solid #f4f4f4;
      span {
        font-size: 13px;
        color: #333333;
      }
      span:last-child {
        color: #5e9df9;
        cursor: pointer;
      }
    }
    .choose_box {
      margin-top: 8px;

      height: calc(100% - 50px);
      width: 100%;
      overflow: scroll;
      padding-left: 16px;
      padding-right: 16px;
      .item {
        margin-bottom: 8px;
      }
      /deep/ .el-tag.el-tag--info {
        border-color: transparent !important;
      }
      /deep/ .el-tag {
        padding: 0 16px;
      }
      /deep/ span {
        color: #666666;
      }
    }
  }
  .dep_footer {
    height: 48px;
    background: #f7f8fa;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 17px;
  }
}
</style>
